package org.myclients.validation.impl;

import org.myclients.domain.Client;
import org.myclients.domain.Login;
import org.myclients.validation.IClientValidator;
import org.myclients.validation.ILoginValidator;
import org.myclients.validation.common.IValidationContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ClientValidator implements IClientValidator {

	@Autowired
	public ILoginValidator loginValidator;

	@Override
	public void validateForSave(Client target, IValidationContext context) {

		context.setField("id", target.getId());
		context.missing();
		
		context.setField("name", target.getName());
		context.required();
		context.text();
		
		context.setField("lastname", target.getLastname());
		context.required();
		context.text();
		
		context.setField("age", target.getAge());
		context.required();
		context.number();
		context.greaterThan(0, "must be greater than zero");
		
		context.setField("logins", target.getLogins());
		context.required();
		context.countIsBetween(1, 5, "must be at least one login");
		
		context.addNested();
		int index = 0;
		for (Login login : target.getLogins())
		{
			context.setIndex(index++);
			context.setTarget(login);
			this.loginValidator.validateForSave(login, context);
		}

		context.removeNested();
	}

	@Override
	public void validateForUpdate(Client target, IValidationContext context) {

		context.setField("id", target.getId());
		context.required();
		context.number();
		
		context.setField("name", target.getName());
		context.required();
		context.text();
		
		context.setField("lastname", target.getLastname());
		context.required();
		context.text();
		
		context.setField("age", target.getAge());
		context.required();
		context.number();
		context.greaterThan(0, "must be greater than zero");
		
		context.setField("logins", target.getLogins());
		context.required();
		context.countIsBetween(1, 5, "must be at least one login");
		
		context.addNested();
		int index = 0;
		for (Login login : target.getLogins())
		{
			context.setIndex(index++);
			context.setTarget(login);
			this.loginValidator.validateForMerge(login, context);
		}

		context.removeNested();
	}
}